﻿using System;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;

namespace TemplateFoundation.UI.WebControls
{
    /// <summary>
    /// Base class for controls which are rendered like property controls in the EPiServer UI
    /// </summary>
    public abstract class PagePropertyStyleControlBase : TableRow, INamingContainer
    {
        /// <summary>
        /// Creates a new control rendered like a property control
        /// </summary>
        protected PagePropertyStyleControlBase()
        {
            Name = "[Name not set]";
            Description = string.Empty;
        }

        /// <summary>
        /// Raises the <see cref="E:System.Web.UI.Control.Init"/> event.
        /// </summary>
        /// <param name="e">An <see cref="T:System.EventArgs"/> object that contains the event data.</param>
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            if (Parent==null)
            {
                throw new NotSupportedException("Parent property was empty");
            }

            if (!(Parent is Table))
            {
                throw new NotSupportedException("This control must be placed inside a Table control");
            }

            var title = new HtmlGenericControl("span");
            title.Attributes.Add("title", Description);
            title.InnerText = Name;

            var titleContainer = new TableHeaderCell {CssClass = "EP-tableCaptionCell"};
            titleContainer.Controls.Add(title);

            var controlContainer = new TableCell();
            controlContainer.Controls.Add(CreatePropertyControl());

            Controls.Add(titleContainer);
            Controls.Add(controlContainer);
        }

        /// <summary>
        /// Gets or sets the control name which is rendered like a property label
        /// </summary>
        public virtual string Name { get; set; }

        /// <summary>
        /// Gets or sets the control description which is rendered like a property help text
        /// </summary>
        public virtual string Description { get; set; }

        /// <summary>
        /// Used to create the control to render as a property control
        /// </summary>
        /// <returns></returns>
        public abstract Control CreatePropertyControl();
    }
}
